<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="30%"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      status-icon
      :rules="rules"
      label-width="120px"
      label-position="top"
      class="myform"
    >
      <slot></slot>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="danger" @click="confirmUpdate">确认修改</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, defineExpose } from "vue";
import { ShowErrorMsg } from "../utils";

// 接收的props
const props: any = defineProps({
  title: String,
  form: Object,
  rules: Object,
  comfirmChange: Function, // 父亲组件把方法传递给子组件, 子组件触发
});
// const form = ref<any>({})   // 内部数据

const formRef = ref<any>();
const dialogVisible = ref<boolean>(false);
const handleClose = () => {
  //关闭弹框
  dialogVisible.value = false;
  formRef.value.resetFields();
};
const showDialog = () => {
  //打开弹框
  dialogVisible.value = true;
};

const confirmUpdate = () => {
  // comfirmChange()
  // 反向props 子改父
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 修改数据的接口
      props.comfirmChange(); //其它三个数据直接用了，方法还要props.
    } else {
      ShowErrorMsg("校验失败");
    }
  });
  // 自定义事件 去实现子改父
};
// setup()钩子函数中调用不同的是：子组件中要通过defineExpose将方法暴露给父组件。
defineExpose({
  dialogVisible, //控制表单显示隐藏的布尔值
  formRef, //表单实例
  handleClose,
  showDialog,
  // form
});
</script>
